// components/markdown-renderer.tsx
'use client'
import ReactMarkdown from 'react-markdown'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { materialDark } from 'react-syntax-highlighter/dist/cjs/styles/prism'
import { Check, Clipboard, ClipboardCheck, Copy } from 'lucide-react'
import { useState } from 'react'
import { Button } from './ui/button'

interface MarkdownRendererProps {
  content: string
}

export default function MarkdownRenderer({ content }: MarkdownRendererProps) {
  const [copiedCode, setCopiedCode] = useState<string | null>(null)

  const handleCopy = async (code: string) => {
    try {
      await navigator.clipboard.writeText(code)
      setCopiedCode(code)
      setTimeout(() => setCopiedCode(null), 2000)
    } catch (err) {
      console.error('复制失败:', err)
    }
  }

  return (
    <ReactMarkdown
      components={{
        code({ node, inline, className, children, ...props }: { node: any, inline: boolean, className: string, children: React.ReactNode }) {
          const match = /language-(\w+)/.exec(className || '')
          return !inline && match ? (
            <div className="relative group">
              <div className="absolute right-2 top-2 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                <Button 
                  onClick={() => handleCopy(String(children))}
                  className="p-1 rounded bg-gray-800 hover:bg-gray-700"
                >
                  {copiedCode === String(children) ? (
                    <Check className="h-4 w-4 text-green-400" />
                  ) : (
                    <Copy className="h-4 w-4 text-gray-300" />
                  )}
                </Button>
              </div>
              <SyntaxHighlighter
                style={materialDark}
                language={match[1]}
                PreTag="div"
                className="rounded-lg p-4 mb-4 relative max-w-[100%]"
                {...props}
              >
                {String(children).replace(/\n$/, '')}
              </SyntaxHighlighter>
            </div>
          ) : (
            <code className={className} {...props}>
              {children}
            </code>
          )
        }
      }}
    >
      {content}
    </ReactMarkdown>
  )
}